package cn.hotel.servlet;

import cn.hotel.pojo.Administrator;
import cn.hotel.service.LogInService;
import cn.hotel.service.LogInServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/logIn")
public class LogInServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();
        String appType = request.getContextPath();

        LogInService logInService = new LogInServiceImpl();
        String type = request.getParameter("type");
        type = type == null? "logIns" : type;
        switch (type){
            case "logIns":
                logIns(request,response,logInService,session,out,appType);
                break;
            case "mistake":
                logIns(request,response,logInService,session,out,appType);
                break;
        }
    }

    private void logIns(HttpServletRequest request, HttpServletResponse response, LogInService logInService, HttpSession session, PrintWriter out, String appType) throws IOException {
        String name =request.getParameter("names");
        String password = request.getParameter("password");

        Map<String ,Object> objectMap = logInService.logIn(name,password);
        if("1".equals(objectMap.get("flag"))){
            Administrator administrators = (Administrator) objectMap.get("data");
            session.setAttribute("administrator",administrators);
            response.sendRedirect(appType+"/orderFormjsp/backgroundimg.jsp");
        }else {

            out.print("<script>alert('账号或密码错误');location.href='"+appType+"/logjsp/login.jsp'</script>");
            out.flush();
        }
    }
}
